import pymysql


class DbUtils:
    # 添加数据库连接 类属性
    __DbConn = None

    # 创建连接
    @classmethod
    def __get_conn(cls):
        # 判断连接是否为空
        if cls.__DbConn is None:
            cls.__DbConn = pymysql.connect(host="localhost", port=3306,
                                           user='root', password='123456', database='girls')
        # 返回我们的连接
        return cls.__DbConn

    # 返回单个数据
    @classmethod
    def select_one(cls, sql):
        result = None
        cur = None
        try:
            cls.__DbConn = cls.__get_conn()  # 获取连接
            cur = cls.__DbConn.cursor()  # 创建游标对象
            cur.execute(sql)  # 执行sql语句
            result = cur.fetchone()  # 返回单个数据
        except Exception as err:
            print("SQL语句查询错误", str(err))
        finally:
            cur.close()  # 关闭游标对象
            cls.__close_conn()  # 关闭db连接
            return result

    # 关闭连接
    @classmethod
    def __close_conn(cls):
        if cls.__DbConn is not None:
            cls.__DbConn.close()
            cls.__DbConn = None

    # 查询全部方法
    # 增加删除，修改一个方法

    @classmethod
    def executeData(cls, sql):
        cur = None
        try:
            cls.__DbConn = cls.__get_conn()  # 获取连接
            cur = cls.__DbConn.cursor()  # 创建游标对象
            cur.execute(sql)  # 执行sql语句
            cls.__DbConn.commit()  # 提交
        except Exception as err:
            cls.__DbConn.rollback()  # 回滚
            print("SQL语句查询错误", str(err))
        finally:
            cur.close()  # 关闭游标对象
            cls.__close_conn()  # 关闭db连接


res = DbUtils.select_one("select * from boys where id =1  order by id desc")
print(res)
